{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# **Guardrails**"
      ],
      "metadata": {
        "id": "JtKpusSwWIZY"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Summary: OpenAI have also included guardrails in the Agents SDK. These come as input guardrails and output guardrails, the input_guardrail checks that the input going into your LLM is \"safe\" and the output_guardrail checks that the output from your LLM is \"safe\".\n",
        "\n",
        "Guardrails run in parallel to your agents, enabling you to do checks and validations of user input. For example, imagine you have an agent that uses a very smart (and hence slow/expensive) model to help with customer requests. You wouldn't want malicious users to ask the model to help them with their math homework. So, you can run a guardrail with a fast/cheap model. If the guardrail detects malicious usage, it can immediately raise an error, which stops the expensive model from running and saves you time/money.\n",
        "\n",
        "There are two kinds of guardrails:\n",
        "\n",
        "1. Input guardrails run on the initial user input\n",
        "2. Output guardrails run on the final agent output\n",
        "\n",
        "Reference:\n",
        "https://openai.github.io/openai-agents-python/guardrails/\n"
      ],
      "metadata": {
        "id": "MagfdaZ7WpAq"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Input guardrails"
      ],
      "metadata": {
        "id": "9naM69-5WOiu"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Input guardrails run in 3 steps:\n",
        "\n",
        "1. First, the guardrail receives the same input passed to the agent.\n",
        "2. Next, the guardrail function runs to produce a GuardrailFunctionOutput, which is then wrapped in an InputGuardrailResult\n",
        "3. Finally, we check if .tripwire_triggered is true. If true, an InputGuardrailTripwireTriggered exception is raised, so you can appropriately respond to the user or handle the exception."
      ],
      "metadata": {
        "id": "Oi2jwrR7XCAc"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Input guardrails are intended to run on user input, so an agent's guardrails only run if the agent is the first agent. You might wonder, why is the guardrails property on the agent instead of passed to Runner.run? It's because guardrails tend to be related to the actual Agent - you'd run different guardrails for different agents, so colocating the code is useful for readability."
      ],
      "metadata": {
        "id": "4-urr2StXat1"
      }
    },
    {
      "cell_type": "markdown",
      "source": [],
      "metadata": {
        "id": "jeAi3NRPeMNh"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Tripwires"
      ],
      "metadata": {
        "id": "Mvwr5szYd1I5"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "If the input or output fails the guardrail, the Guardrail can signal this with a tripwire. As soon as we see a guardrail that has triggered the tripwires, we immediately raise a {Input,Output}GuardrailTripwireTriggered exception and halt the Agent execution."
      ],
      "metadata": {
        "id": "dg7uTOJhd9_6"
      }
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PdKwzEluDBN7"
      },
      "source": [
        "# Install openai-agents SDK"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "3QdkOviEB2ay"
      },
      "outputs": [],
      "source": [
        "!pip install -Uq openai-agents pydantic"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7yD91lz4DIAx"
      },
      "source": [
        "# Make your Notebook capable of running asynchronous functions.\n",
        "Both Jupyter notebooks and Python’s asyncio library utilize event loops, but they serve different purposes and can sometimes interfere with each other.\n",
        "\n",
        "The nest_asyncio library allows the existing event loop to accept nested event loops, enabling asyncio code to run within environments that already have an event loop, such as Jupyter notebooks.\n",
        "\n",
        "In summary, both Jupyter notebooks and Python’s asyncio library utilize event loops to manage asynchronous operations. When working within Jupyter notebooks, it’s essential to be aware of the existing event loop to effectively run asyncio code without conflicts."
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import nest_asyncio\n",
        "nest_asyncio.apply()"
      ],
      "metadata": {
        "id": "C8YXyIpiZ9v4"
      },
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "XnusaX_RWF22"
      },
      "outputs": [],
      "source": [
        "from pydantic import BaseModel\n",
        "from agents import (\n",
        "    Agent,\n",
        "    GuardrailFunctionOutput,\n",
        "    InputGuardrailTripwireTriggered,\n",
        "    OutputGuardrailTripwireTriggered,\n",
        "    RunContextWrapper,\n",
        "    Runner,\n",
        "    TResponseInputItem,\n",
        "    input_guardrail,\n",
        "    output_guardrail,\n",
        "    AsyncOpenAI,\n",
        "    OpenAIChatCompletionsModel,\n",
        "    RunConfig\n",
        ")\n",
        "from google.colab import userdata\n"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "gemini_api_key = userdata.get(\"GEMINI_API_KEY\")\n",
        "\n",
        "\n",
        "# Check if the API key is present; if not, raise an error\n",
        "if not gemini_api_key:\n",
        "    raise ValueError(\"GEMINI_API_KEY is not set. Please ensure it is defined in your .env file.\")"
      ],
      "metadata": {
        "id": "oPvcFwItoKqw"
      },
      "execution_count": 9,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#Reference: https://ai.google.dev/gemini-api/docs/openai\n",
        "external_client = AsyncOpenAI(\n",
        "    api_key=gemini_api_key,\n",
        "    base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\",\n",
        ")\n",
        "\n",
        "model = OpenAIChatCompletionsModel(\n",
        "    model=\"gemini-2.0-flash\",\n",
        "    openai_client=external_client\n",
        ")\n",
        "\n",
        "config = RunConfig(\n",
        "    model=model,\n",
        "    model_provider=external_client,\n",
        "    tracing_disabled=True\n",
        ")\n"
      ],
      "metadata": {
        "id": "ci9rBxqfnyNm"
      },
      "execution_count": 21,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Implementation of Input Guardrail:\n",
        "Checks that the input going into your LLM is \"safe\""
      ],
      "metadata": {
        "id": "SR8ARQZGAItU"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "class MathHomeworkOutput(BaseModel):\n",
        "    is_math_homework: bool\n",
        "    reasoning: str\n",
        "\n",
        "guardrail_agent = Agent(\n",
        "    name=\"Guardrail check\",\n",
        "    instructions=\"Check if the user is asking you to do their math homework.\",\n",
        "    output_type=MathHomeworkOutput,\n",
        ")\n",
        "\n",
        "\n",
        "@input_guardrail\n",
        "async def math_guardrail(\n",
        "    ctx: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]\n",
        ") -> GuardrailFunctionOutput:\n",
        "    result = await Runner.run(guardrail_agent, input, context=ctx.context, run_config = config)\n",
        "\n",
        "    return GuardrailFunctionOutput(\n",
        "        output_info=result.final_output,\n",
        "        # tripwire_triggered=False #result.final_output.is_math_homework,\n",
        "        tripwire_triggered=result.final_output.is_math_homework,\n",
        "    )"
      ],
      "metadata": {
        "id": "PYFkT_B-YaYh"
      },
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "agent = Agent(\n",
        "    name=\"Customer support agent\",\n",
        "    instructions=\"You are a customer support agent. You help customers with their questions.\",\n",
        "    input_guardrails=[math_guardrail],\n",
        ")"
      ],
      "metadata": {
        "id": "TE2j1WJ-YjNK"
      },
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# This should trip the guardrail\n",
        "\n",
        "try:\n",
        "    result = await Runner.run(agent, \"Hello, can you help me solve for x: 2x + 3 = 11?\", run_config = config)\n",
        "    print(\"Guardrail didn't trip - this is unexpected\")\n",
        "    print(result.final_output)\n",
        "\n",
        "except InputGuardrailTripwireTriggered:\n",
        "    print(\"Math homework guardrail tripped\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xg5g0KaBYuVl",
        "outputId": "405dbf8f-af65-4eb6-a716-6e69e3464f7a"
      },
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Math homework guardrail tripped\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "try:\n",
        "    result = await Runner.run(agent, \"Hello\", run_config = config)\n",
        "    print(result.final_output)\n",
        "\n",
        "except InputGuardrailTripwireTriggered:\n",
        "    print(\"Math homework guardrail tripped\")"
      ],
      "metadata": {
        "id": "o4TmzNa_K7TJ",
        "outputId": "aecc06ea-6002-4bcc-db19-ed37b6bb8977",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Hi there! How can I help you today?\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [],
      "metadata": {
        "id": "8KU3X_gDsS0u"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Implementation of Onput Guardrail:\n",
        "The output guardrail checks that the output from your LLM is \"safe\"."
      ],
      "metadata": {
        "id": "uARwzOgjscIi"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "class MessageOutput(BaseModel):\n",
        "    response: str\n",
        "\n",
        "class MathOutput(BaseModel):\n",
        "    is_math: bool\n",
        "    reasoning: str\n",
        "\n",
        "guardrail_agent2 = Agent(\n",
        "    name=\"Guardrail check\",\n",
        "    instructions=\"Check if the output includes any math.\",\n",
        "    output_type=MathOutput,\n",
        ")\n",
        "\n",
        "@output_guardrail\n",
        "async def math_guardrail2(\n",
        "    ctx: RunContextWrapper, agent: Agent, output: MessageOutput\n",
        ") -> GuardrailFunctionOutput:\n",
        "    result = await Runner.run(guardrail_agent2, output.response, context=ctx.context, run_config = config)\n",
        "\n",
        "    return GuardrailFunctionOutput(\n",
        "        output_info=result.final_output,\n",
        "        tripwire_triggered=result.final_output.is_math,\n",
        "    )"
      ],
      "metadata": {
        "id": "zWXqInCSsoUw"
      },
      "execution_count": 16,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "agent2 = Agent(\n",
        "    name=\"Customer support agent\",\n",
        "    instructions=\"You are a customer support agent. You help customers with their questions.\",\n",
        "    output_guardrails=[math_guardrail2],\n",
        "    output_type=MessageOutput,\n",
        ")"
      ],
      "metadata": {
        "id": "2OiAB8_RQ5pz"
      },
      "execution_count": 17,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# This should trip the guardrail\n",
        "try:\n",
        "    await Runner.run(agent2, \"Hello, can you help me solve for x: 2x + 3 = 11?\", run_config = config)\n",
        "    print(\"Guardrail didn't trip - this is unexpected\")\n",
        "\n",
        "except OutputGuardrailTripwireTriggered:\n",
        "    print(\"Math output guardrail tripped\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "mj6qZTgrRz4T",
        "outputId": "5bc6a1c2-8ee8-4f77-d222-810c53d3bc23"
      },
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Math output guardrail tripped\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# PIAIC Gaurdrails example"
      ],
      "metadata": {
        "id": "oA4GjcbsQVxb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import asyncio\n",
        "from pydantic import BaseModel\n",
        "from agents import (\n",
        "    Agent,\n",
        "    GuardrailFunctionOutput,\n",
        "    InputGuardrail,\n",
        "    InputGuardrailTripwireTriggered,\n",
        "    RunContextWrapper,\n",
        "    Runner,\n",
        ")\n",
        "\n",
        "# Define the output model for the guardrail agent\n",
        "class PIAICRelevanceOutput(BaseModel):\n",
        "    is_piaic_relevant: bool\n",
        "    reasoning: str\n",
        "\n",
        "# Create the guardrail agent to check if input is PIAIC-related\n",
        "guardrail_agent = Agent(\n",
        "    name=\"PIAIC_Relevance_Check\",\n",
        "    instructions=(\n",
        "        \"You are a guardrail agent that checks if the user's input is related to PIAIC (Presidential Initiative for Artificial Intelligence and Computing) topics, \"\n",
        "        \"such as Artificial Intelligence, Cloud Native Computing, Blockchain, Internet of Things (IoT), or other PIAIC courses. \"\n",
        "        \"Determine if the input is relevant to PIAIC. \"\n",
        "        \"Return a structured output with 'is_piaic_relevant' as a boolean and 'reasoning' explaining your decision.\"\n",
        "    ),\n",
        "    output_type=PIAICRelevanceOutput,\n",
        ")\n",
        "\n",
        "# Define the input guardrail function\n",
        "async def piaic_relevance_guardrail(\n",
        "    ctx: RunContextWrapper[None],\n",
        "    agent: Agent,\n",
        "    input: str | list,\n",
        ") -> GuardrailFunctionOutput:\n",
        "    result = await Runner.run(guardrail_agent, input, context=ctx.context, run_config = config)\n",
        "    final_output = result.final_output_as(PIAICRelevanceOutput)\n",
        "    return GuardrailFunctionOutput(\n",
        "        output_info=final_output,\n",
        "        tripwire_triggered=not final_output.is_piaic_relevant,\n",
        "    )\n",
        "\n",
        "# Create the main PIAIC agent\n",
        "piaic_agent = Agent(\n",
        "    name=\"PIAIC_Assistant\",\n",
        "    instructions=(\n",
        "        \"You are a helpful assistant for PIAIC-related questions. \"\n",
        "        \"Answer questions about PIAIC courses, such as AI, Cloud Native Computing, Blockchain, IoT, or other PIAIC initiatives. \"\n",
        "        \"Provide accurate and concise information.\"\n",
        "    ),\n",
        "    input_guardrails=[InputGuardrail(guardrail_function=piaic_relevance_guardrail)],\n",
        ")\n",
        "\n",
        "\n",
        "try:\n",
        "    result = await Runner.run(piaic_agent, \"What is the curriculum for PIAIC's AI course?\", run_config = config)\n",
        "    print(\"Response:\", result.final_output)\n",
        "except InputGuardrailTripwireTriggered as e:\n",
        "    print(\"Guardrail tripped: Input is not PIAIC-related.\")\n",
        "\n",
        "\n",
        "\n"
      ],
      "metadata": {
        "id": "lPyCh6q8QZeW",
        "outputId": "904863cd-9938-4300-d08d-87b6504dd0c7",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 23,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Response: The PIAIC AI course curriculum is designed to provide a comprehensive foundation in Artificial Intelligence, covering both theoretical concepts and practical applications. Here's a breakdown of the key modules:\n",
            "\n",
            "1.  **Python Programming:**\n",
            "    *   Fundamentals of Python syntax and data structures.\n",
            "    *   Working with libraries like NumPy, Pandas, and Matplotlib for data manipulation and visualization.\n",
            "\n",
            "2.  **Mathematics for AI:**\n",
            "    *   Linear Algebra: Vectors, matrices, and their applications in AI.\n",
            "    *   Calculus: Derivatives, gradients, and optimization techniques.\n",
            "    *   Probability and Statistics: Probability distributions, hypothesis testing, and statistical inference.\n",
            "\n",
            "3.  **Machine Learning:**\n",
            "    *   Supervised Learning: Regression and Classification algorithms (e.g., linear regression, logistic regression, support vector machines, decision trees, random forests).\n",
            "    *   Unsupervised Learning: Clustering algorithms (e.g., k-means, hierarchical clustering), dimensionality reduction techniques (e.g., PCA).\n",
            "    *   Model evaluation, selection, and hyperparameter tuning.\n",
            "\n",
            "4.  **Deep Learning:**\n",
            "    *   Neural Networks: Architecture, activation functions, and training algorithms (e.g., backpropagation).\n",
            "    *   Convolutional Neural Networks (CNNs): Image recognition and computer vision tasks.\n",
            "    *   Recurrent Neural Networks (RNNs): Natural language processing and sequential data analysis.\n",
            "    *   Deep learning frameworks like TensorFlow and Keras.\n",
            "\n",
            "5.  **Natural Language Processing (NLP):**\n",
            "    *   Text preprocessing techniques (e.g., tokenization, stemming, lemmatization).\n",
            "    *   Sentiment analysis, text classification, and named entity recognition.\n",
            "    *   Language models and text generation.\n",
            "\n",
            "6.  **Computer Vision:**\n",
            "    *   Image processing techniques (e.g., filtering, edge detection).\n",
            "    *   Object detection and image segmentation.\n",
            "    *   Applications of computer vision in various domains.\n",
            "\n",
            "7.  **Reinforcement Learning:**\n",
            "    *   Markov Decision Processes (MDPs) and dynamic programming.\n",
            "    *   Q-learning, SARSA, and Deep Reinforcement Learning algorithms.\n",
            "    *   Applications in robotics, game playing, and decision-making.\n",
            "\n",
            "This curriculum may be subject to minor adjustments to keep it up-to-date with the latest advancements in the field. You can always check the official PIAIC website or course materials for the most current and detailed information.\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Test with non-PIAIC input\n",
        "try:\n",
        "    result = await Runner.run(piaic_agent, \"How do I bake a chocolate cake?\", run_config = config)\n",
        "    print(\"Response:\", result.final_output)\n",
        "except InputGuardrailTripwireTriggered as e:\n",
        "    print(\"Guardrail tripped: Input is not PIAIC-related.\")"
      ],
      "metadata": {
        "id": "0TFr3f5MQaWy",
        "outputId": "e57b5f83-1bd0-4d72-a554-b1a034ba8d48",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 24,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Guardrail tripped: Input is not PIAIC-related.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Input and Out Guardrails Example"
      ],
      "metadata": {
        "id": "XFadgpFkWwgX"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import asyncio\n",
        "from pydantic import BaseModel\n",
        "from agents import (\n",
        "    Agent,\n",
        "    GuardrailFunctionOutput,\n",
        "    InputGuardrail,\n",
        "    InputGuardrailTripwireTriggered,\n",
        "    OutputGuardrail,\n",
        "    OutputGuardrailTripwireTriggered,\n",
        "    RunContextWrapper,\n",
        "    Runner,\n",
        ")\n",
        "\n",
        "# Define the output model for the guardrail agents\n",
        "class PIAICRelevanceOutput(BaseModel):\n",
        "    is_piaic_relevant: bool\n",
        "    reasoning: str\n",
        "\n",
        "# Create the input guardrail agent to check if input is PIAIC-related\n",
        "input_guardrail_agent = Agent(\n",
        "    name=\"PIAIC_Input_Relevance_Check\",\n",
        "    instructions=(\n",
        "        \"You are a guardrail agent that checks if the user's input is related to PIAIC (Presidential Initiative for Artificial Intelligence and Computing) topics, \"\n",
        "        \"such as Artificial Intelligence, Cloud Native Computing, Blockchain, Internet of Things (IoT), or other PIAIC courses. \"\n",
        "        \"Determine if the input is relevant to PIAIC. \"\n",
        "        \"Return a structured output with 'is_piaic_relevant' as a boolean and 'reasoning' explaining your decision.\"\n",
        "    ),\n",
        "    output_type=PIAICRelevanceOutput,\n",
        ")\n",
        "\n",
        "# Create the output guardrail agent to check if output is PIAIC-related\n",
        "output_guardrail_agent = Agent(\n",
        "    name=\"PIAIC_Output_Relevance_Check\",\n",
        "    instructions=(\n",
        "        \"You are a guardrail agent that checks if the agent's response is related to PIAIC (Presidential Initiative for Artificial Intelligence and Computing) topics, \"\n",
        "        \"such as Artificial Intelligence, Cloud Native Computing, Blockchain, Internet of Things (IoT), or other PIAIC courses. \"\n",
        "        \"Determine if the response content is relevant to PIAIC. \"\n",
        "        \"Return a structured output with 'is_piaic_relevant' as a boolean and 'reasoning' explaining your decision.\"\n",
        "    ),\n",
        "    output_type=PIAICRelevanceOutput,\n",
        ")\n",
        "\n",
        "# Define the input guardrail function\n",
        "async def piaic_input_relevance_guardrail(\n",
        "    ctx: RunContextWrapper[None],\n",
        "    agent: Agent,\n",
        "    input: str | list,\n",
        ") -> GuardrailFunctionOutput:\n",
        "    result = await Runner.run(input_guardrail_agent, input, context=ctx.context, run_config = config)\n",
        "    final_output = result.final_output_as(PIAICRelevanceOutput)\n",
        "    return GuardrailFunctionOutput(\n",
        "        output_info=final_output,\n",
        "        tripwire_triggered=not final_output.is_piaic_relevant,\n",
        "    )\n",
        "\n",
        "# Define the output guardrail function\n",
        "async def piaic_output_relevance_guardrail(\n",
        "    ctx: RunContextWrapper[None],\n",
        "    agent: Agent,\n",
        "    output: str | list,\n",
        ") -> GuardrailFunctionOutput:\n",
        "    result = await Runner.run(output_guardrail_agent, output, context=ctx.context, run_config = config)\n",
        "    final_output = result.final_output_as(PIAICRelevanceOutput)\n",
        "    return GuardrailFunctionOutput(\n",
        "        output_info=final_output,\n",
        "        tripwire_triggered=not final_output.is_piaic_relevant,\n",
        "    )\n",
        "\n",
        "# Create the main PIAIC agent with both input and output guardrails\n",
        "piaic_agent = Agent(\n",
        "    name=\"PIAIC_Assistant\",\n",
        "    instructions=(\n",
        "        \"You are a helpful assistant for PIAIC-related questions. \"\n",
        "        \"Answer questions about PIAIC courses, such as AI, Cloud Native Computing, Blockchain, IoT, or other PIAIC initiatives. \"\n",
        "        \"Provide accurate and concise information.\"\n",
        "    ),\n",
        "    input_guardrails=[InputGuardrail(guardrail_function=piaic_input_relevance_guardrail)],\n",
        "    output_guardrails=[OutputGuardrail(guardrail_function=piaic_output_relevance_guardrail)],\n",
        ")\n",
        "\n",
        "\n",
        "try:\n",
        "    result = await Runner.run(piaic_agent, \"What is the curriculum for PIAIC's AI course?\", run_config = config)\n",
        "    print(\"Response:\", result.final_output)\n",
        "except InputGuardrailTripwireTriggered as e:\n",
        "    print(\"Input Guardrail tripped: Input is not PIAIC-related.\")\n",
        "except OutputGuardrailTripwireTriggered as e:\n",
        "    print(\"Output Guardrail tripped: Response is not PIAIC-related.\")\n",
        "\n",
        ""
      ],
      "metadata": {
        "id": "6m1rhzjERWy-",
        "outputId": "42b332fc-7625-4cf1-d5e2-dd9b28b56aa2",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Response: The PIAIC AI course curriculum is designed to provide a comprehensive understanding of Artificial Intelligence, covering both theoretical foundations and practical applications. Here's a breakdown of the key modules:\n",
            "\n",
            "**Module 1: Python Programming**\n",
            "\n",
            "*   Introduction to Python\n",
            "*   Data Types and Variables\n",
            "*   Operators and Expressions\n",
            "*   Control Flow (if/else statements, loops)\n",
            "*   Functions\n",
            "*   Data Structures (Lists, Tuples, Dictionaries, Sets)\n",
            "*   File Handling\n",
            "*   Object-Oriented Programming (OOP)\n",
            "\n",
            "**Module 2: Mathematics for AI**\n",
            "\n",
            "*   Linear Algebra: Vectors, Matrices, Operations, Eigenvalues, Eigenvectors\n",
            "*   Calculus: Derivatives, Integrals, Optimization\n",
            "*   Probability and Statistics: Probability Distributions, Hypothesis Testing, Statistical Inference\n",
            "\n",
            "**Module 3: Machine Learning**\n",
            "\n",
            "*   Introduction to Machine Learning\n",
            "*   Supervised Learning:\n",
            "    *   Regression (Linear Regression, Polynomial Regression)\n",
            "    *   Classification (Logistic Regression, Support Vector Machines, Decision Trees, Random Forests)\n",
            "*   Unsupervised Learning:\n",
            "    *   Clustering (K-Means, Hierarchical Clustering)\n",
            "    *   Dimensionality Reduction (PCA)\n",
            "*   Model Evaluation and Selection\n",
            "*   Regularization\n",
            "*   Bias-Variance Tradeoff\n",
            "\n",
            "**Module 4: Deep Learning**\n",
            "\n",
            "*   Introduction to Neural Networks\n",
            "*   Activation Functions\n",
            "*   Backpropagation\n",
            "*   Optimization Algorithms (Gradient Descent, Adam)\n",
            "*   Convolutional Neural Networks (CNNs)\n",
            "*   Recurrent Neural Networks (RNNs)\n",
            "*   Long Short-Term Memory (LSTM) Networks\n",
            "*   Generative Adversarial Networks (GANs)\n",
            "\n",
            "**Module 5: Natural Language Processing (NLP)**\n",
            "\n",
            "*   Text Preprocessing\n",
            "*   Tokenization\n",
            "*   Stemming and Lemmatization\n",
            "*   Bag of Words\n",
            "*   TF-IDF\n",
            "*   Word Embeddings (Word2Vec, GloVe)\n",
            "*   Sentiment Analysis\n",
            "*   Text Classification\n",
            "\n",
            "**Module 6: Computer Vision**\n",
            "\n",
            "*   Image Processing Fundamentals\n",
            "*   Feature Extraction\n",
            "*   Object Detection\n",
            "*   Image Segmentation\n",
            "*   Image Classification\n",
            "\n",
            "**Module 7: Reinforcement Learning**\n",
            "\n",
            "*   Introduction to Reinforcement Learning\n",
            "*   Markov Decision Processes (MDPs)\n",
            "*   Q-Learning\n",
            "*   Deep Q-Networks (DQN)\n",
            "\n",
            "**Module 8: AI Ethics and Societal Impact**\n",
            "\n",
            "*   Bias in AI\n",
            "*   Fairness and Accountability\n",
            "*   Privacy and Security\n",
            "*   Responsible AI Development\n",
            "\n",
            "**Tools and Technologies:**\n",
            "\n",
            "Throughout the course, students gain hands-on experience with popular AI tools and libraries such as:\n",
            "\n",
            "*   Python\n",
            "*   NumPy\n",
            "*   Pandas\n",
            "*   Scikit-learn\n",
            "*   TensorFlow\n",
            "*   Keras\n",
            "*   PyTorch\n",
            "*   NLTK\n",
            "*   OpenCV\n",
            "\n",
            "**Important Considerations:**\n",
            "\n",
            "*   This curriculum may be subject to minor revisions and updates.  It's always best to check the official PIAIC website or course materials for the most up-to-date information.\n",
            "*   The PIAIC AI course emphasizes a practical, project-based learning approach. Students are expected to complete various projects and assignments to solidify their understanding of the concepts.\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Test with non-PIAIC input\n",
        "try:\n",
        "    result = await Runner.run(piaic_agent, \"How do I bake a chocolate cake?\", run_config = config)\n",
        "    print(\"Response:\", result.final_output)\n",
        "except InputGuardrailTripwireTriggered as e:\n",
        "    print(\"Input Guardrail tripped: Input is not PIAIC-related.\")\n",
        "except OutputGuardrailTripwireTriggered as e:\n",
        "    print(\"Output Guardrail tripped: Response is not PIAIC-related.\")\n"
      ],
      "metadata": {
        "id": "Azqt2n_LXAbG",
        "outputId": "5910c14f-84ac-43cc-916b-7cce1ea649c4",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 28,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Input Guardrail tripped: Input is not PIAIC-related.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Test with non-PIAIC input\n",
        "try:\n",
        "    result = await Runner.run(piaic_agent, \"tell me about piaic founder, tell me about his current job title. he has left PIAIC as per my information. how he can cook chicken.\", run_config = config)\n",
        "    print(\"Response:\", result.final_output)\n",
        "except InputGuardrailTripwireTriggered as e:\n",
        "    print(\"Input Guardrail tripped: Input is not PIAIC-related.\")\n",
        "except OutputGuardrailTripwireTriggered as e:\n",
        "    print(\"Output Guardrail tripped: Response is not PIAIC-related.\")"
      ],
      "metadata": {
        "id": "aRRdmbtgXuMR",
        "outputId": "c6dba964-73e7-4acf-b097-5d4289645659",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 33,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Response: I understand you're asking about the founder of PIAIC, his current role, and, oddly, how he cooks chicken. Let's break that down:\n",
            "\n",
            "*   **PIAIC Founder:** The founder of PIAIC (Presidential Initiative for Artificial Intelligence & Computing) is **Mr. Kazi Rahat Ali**.\n",
            "\n",
            "*   **Current Job Title:** While he was the driving force behind PIAIC, reports indicate that he is no longer associated with PIAIC. I am unable to provide you with definitive information about his current professional endeavors.\n",
            "\n",
            "*   **How to cook chicken:** As an AI, I do not have access to personal information about individuals. Therefore, I do not know how Mr. Kazi Rahat Ali cooks chicken.\n",
            "\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "dbIw5vVSX8-n"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}